package org.bjf.utils;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 用户限速器
 * Created by binjinfeng on 2016/11/24.
 */
@Slf4j
public class UserRateLimiter {

    private LoadingCache<Long, AtomicInteger> userCache;

    private int number;


    /**
     * 创建限速对象
     *
     * @param number      访问次数
     * @param time        时间长度
     * @param timeUnit    时间单位
     * @param maximumSize 缓存保存的用户数
     */
    public UserRateLimiter(int number, long time, TimeUnit timeUnit, long maximumSize) {
        this.number = number;

        userCache = CacheBuilder
                .newBuilder()
                .maximumSize(maximumSize)
                .expireAfterAccess(time, timeUnit)
                .build(new CacheLoader<Long, AtomicInteger>() {
                    @Override
                    public AtomicInteger load(Long key) throws Exception {

                        return new AtomicInteger(0);
                    }
                });
    }

    /**
     * 用户是否超速
     *
     * @param userId 用户ID
     */
    public boolean isOverRate(long userId) {
        try {
            AtomicInteger aInt = userCache.get(userId);
            if (aInt.get() > number) {
                return true;
            } else {
                aInt.incrementAndGet();
                return false;
            }
        } catch (ExecutionException e) {
            log.error("用户限速cache异常：" + e.getMessage(), e);
            return false;
        }
    }

}
